//
//  PictureSelectorViewController.swift
//  Weibo
//
//  Created by 孙成宇 on 15/12/4.
//  Copyright © 2015年 mac. All rights reserved.
//

import UIKit

private let reuseIdentifier = "Cell"
private let pictureCellMargin: CGFloat = 10
private let rowCount : CGFloat = 4
private let maxImageCount = 3
class PictureSelectorViewController: UICollectionViewController {


     lazy var imageList = [UIImage]()

    init(){
        let w = (screenW - (rowCount + 1) * pictureCellMargin) / rowCount
        let layout = UICollectionViewFlowLayout()

        layout.itemSize = CGSize(width: w, height: w)

        layout.sectionInset = UIEdgeInsets(top: pictureCellMargin, left: pictureCellMargin, bottom: 0, right: pictureCellMargin)
        layout.minimumInteritemSpacing = pictureCellMargin
        layout.minimumLineSpacing = pictureCellMargin



        super.init(collectionViewLayout: layout)


    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func viewDidLoad() {
        super.viewDidLoad()


// Register cell classes
        self.collectionView!.registerClass(PictureSeletorCell.self, forCellWithReuseIdentifier: reuseIdentifier)

    }


// MARK: UICollectionViewDataSource
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

        let detla = imageList.count == maxImageCount ? 0 : 1
        let count = imageList.count + detla
        return count
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as!PictureSeletorCell


        cell.backgroundColor = UIColor.randomColor()

        cell.selectorDelegate = self
        if indexPath.item == imageList.count {

          cell.iconImage = nil

        }else{
       cell.iconImage  = imageList[indexPath.item]


        }


        return cell
    }

}

extension PictureSelectorViewController:PictureSeletorDelegate {



    func userWiiDelePicture(cell: PictureSeletorCell) {

        let indexpath = collectionView!.indexPathForCell(cell)!

        imageList.removeAtIndex(indexpath.item)

        collectionView?.reloadData()




}
    func userWillChosePicture(cell: PictureSeletorCell) {

        let piker = UIImagePickerController()

        piker.delegate = self


        presentViewController(piker, animated: true, completion: nil)



    }

}
extension PictureSelectorViewController: UIImagePickerControllerDelegate,UINavigationControllerDelegate {
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        //print(image)

        imageList.append(image)
        collectionView?.reloadData()


     //   print(editingInfo)
        dismissViewControllerAnimated(true, completion: nil)

    }


}


////----------------------------------------------
@objc protocol PictureSeletorDelegate: NSObjectProtocol {


    optional func userWillChosePicture(cell: PictureSeletorCell)
    func userWiiDelePicture(cell: PictureSeletorCell)

}




class PictureSeletorCell: UICollectionViewCell {
    var iconImage : UIImage? {
        didSet {
      deleteBtn.hidden = iconImage == nil
            if iconImage == nil {


            return
            }
            addBtn.setImage(iconImage, forState: .Normal)
        }
    }


    //MARK: 响应方法
    @objc private func addBtnDidClick() {
selectorDelegate?.userWillChosePicture!(self)


    }

    @objc private func deleteBtnDidClick() {
        selectorDelegate?.userWiiDelePicture(self)
    }

    //声明一个弱引用的代理
    weak var  selectorDelegate: PictureSeletorDelegate?

    //MARK: 重写构造方法
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }


    //MARK: 设置UI 及布局
    private func setupUI() {
        contentView.addSubview(addBtn)
        contentView.addSubview(deleteBtn)

        //设置布局
        addBtn.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView.snp_edges)
        }

        deleteBtn.snp_makeConstraints { (make) -> Void in
            make.right.equalTo(contentView.snp_right)
            make.top.equalTo(contentView.snp_top)
        }
        
        //添加点击事件
        addBtn.addTarget(self, action: "addBtnDidClick", forControlEvents: .TouchUpInside)
        deleteBtn.addTarget(self, action: "deleteBtnDidClick", forControlEvents: .TouchUpInside)

        addBtn.imageView?.contentMode = . ScaleAspectFill
        
    }
    
    //MARK: 懒加载所有的子控件
    private lazy var addBtn: UIButton = UIButton(imageName: nil, backImage: "compose_pic_add")
    private lazy var deleteBtn: UIButton = UIButton(imageName: nil, backImage: "compose_photo_close")
}

